//引入菜单的接口方法
import { Message } from "element-ui";
import { goodslist, allGoods } from "../../request/api";

export default {
    state: {
        goodsList: [],//这是goods的初始数组
        is: {//判断是否显示dialog 弹窗
            show: false
        },
        total: 0, //这是页码总数
        pageNum: 1,//这是页码数
        pageSize: 4,//这是条数
    },
    getters: {},
    mutations: {
        //修改goods数据 初始数据
        REQ_GOODS(state, payload) {
            state.goodsList = payload;
        },

        //修改dialog弹窗
        changeDialog(state, payload) {
            state.is.show = payload;
        },

        //修改总数
        changeTotal(state, payload) {
            state.total = payload;
        },

        //修改Page 页码
        changePage(state, payload) {
            state.pageNum = payload;
        }
    },
    actions: {
        //异步操作 获取数据 goods
        getGoods(context) {
            goodslist({ page: context.state.pageNum, size: context.state.pageSize }).then(res => {
                //判断是否正确获取数据
                if (res.code == 200) {
                    let list = res.list ? res.list : [];
                    //解决删除的BUG
                    if (context.state.pageNum != 1 && list.length == 0) {
                        //切换到前一页
                        context.dispatch('getPage', context.state.pageNum - 1);
                        return
                    }
                    context.commit("REQ_GOODS", res.list);
                } else {
                    Message.error(res.msg);
                }
            });
        },

        //获取总条数
        getGoodsTotal(context) {
            //获取总条数的接口
            allGoods().then(res => {
                if (res.code == 200) {
                    //传给 mutations  修改数据
                    context.commit('changeTotal', res.list[0].total);
                } else {
                    Message.error(res.msg);
                }
            })
        },

        //切换页码
        getPage(context, payload) {
            //修改页码
            context.commit('changePage', payload);
            //重新获取数据
            context.dispatch('getGoods');
        }
    },
    namespaced: true
}